package com.cc.shiro;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class SecurityRealm extends AuthorizingRealm {

	@Autowired
	// private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		if (StringUtils.isNotEmpty(userName)) {
			List<String> permissions = this.userService.selectUserPermissions(userName);
			for (String permission : permissions) {
				if (StringUtils.isNotEmpty(permission)) {
					info.addStringPermission(permission);
				}
			}
			return info;
		} else {
			return null;
		}
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		String userName = (String) authcToken.getPrincipal();
		TfUser user = this.userService.getTFUserByUserCode(userName);
		if (user != null) {
			// return new SimpleAuthenticationInfo(user.getUserCode(),
			// user.getPassword(), getName());
			return new SimpleAuthenticationInfo(user.getUserid(), "", getName());

		} else {
			return null;
		}
	}

}
